//
//  DXRefreshControl.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/12.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit

enum DXReFreshState:Int {
//   普通状态
    case NormalState = 0
//   可以刷新的临界状态
    case ReadyState = 1
//   正在刷新状态
    case FreshingState = 2
}
let KHeight:CGFloat = 35

class DXRefreshControl: UIControl {
   
    var isFreshing:Bool = false
    
   private var oldState:DXReFreshState = .NormalState
    
   private var reFreshstate:DXReFreshState = .NormalState {
        didSet{
            if reFreshstate == .NormalState{
//                正常
                if oldState == .FreshingState {
                    var contentInset = scrollerView!.contentInset
                    contentInset.top = contentInset.top - KHeight
                    scrollerView!.contentInset = contentInset
                    actIndicator.stopAnimating()
                }
                isFreshing = false
                arrowView.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                  self.arrowView.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
            }else if reFreshstate == .ReadyState {
//                就绪
                isFreshing = false
           UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
        })
                messageLabel.text = "放松刷新"
            }else{
//                刷新中
                 isFreshing = true
                arrowView.hidden = true
                actIndicator.startAnimating()
                 messageLabel.text = "正在刷新..."
                var contentInset = scrollerView!.contentInset
                    contentInset.top = KHeight + contentInset.top
                   scrollerView!.contentInset = contentInset
                sendActionsForControlEvents(.ValueChanged)
            }
             oldState = reFreshstate
        }
    }
   private var scrollerView:UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
// MARK:  外界回调方法,停止刷新
    func endRefreshing(){
     reFreshstate = .NormalState
    
    }
//    MARK:初始化子控件
    private func setUpUI(){
   
    backgroundColor =  UIColor.redColor()
//      添加子控件
        addSubview(arrowView)
        addSubview(messageLabel)
        addSubview(actIndicator)
//        添加约束
        arrowView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowView.snp_trailing).offset(3)
            make.centerY.equalTo(arrowView)
        }
        actIndicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowView)
        }

    }
//    MARK:重写添加到父控件时的方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if newSuperview!.isKindOfClass(UIScrollView.self){
        super.willMoveToSuperview(newSuperview)
            let superView = newSuperview as! UIScrollView
            scrollerView = superView
//          添加KVO监听
            superView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
            self.frame = CGRectMake(0, -KHeight, scrollerView!.frame.width, KHeight)
        }
    }
    
//   监听代理
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if let vaule = change?["new"] as? NSValue {
            let contentInsetTop = scrollerView?.contentInset.top ?? 0
    //            临界值
          let max = contentInsetTop + KHeight
          let offPoint = vaule.CGPointValue()
           
          let offY:CGFloat = offPoint.y
//             logPrint(offY)
            if reFreshstate != .FreshingState {
            if  scrollerView!.dragging {
//            在拉动
                if offY > -(max) {
//             正常状态
            if reFreshstate != .NormalState {
              reFreshstate = .NormalState
//              logPrint("正常")
              }
            }else{
                    
          if reFreshstate != .ReadyState{
//               logPrint("就绪")
              reFreshstate = .ReadyState
                }
              }
            }else{
//            没拉动
                if offY <= -(max) && oldState == .ReadyState{
                reFreshstate = .FreshingState
//                 logPrint("刷新")
             }
           }
        }
    }
}
//    移除监听者
    deinit{
    self.scrollerView!.removeObserver(self, forKeyPath: "contentOffset")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    MARK:懒加载
  private  lazy var arrowView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
  private  lazy var messageLabel:UILabel = {
    
        let messageLabel = UILabel()
        messageLabel.textColor = UIColor.grayColor()
        messageLabel.text = "下拉刷新"
        messageLabel.font =  UIFont.systemFontOfSize(14)
        messageLabel.sizeToFit()
        return messageLabel
    }()
    
   private lazy var actIndicator:UIActivityIndicatorView = {
        let actIndicator = UIActivityIndicatorView()
        actIndicator.activityIndicatorViewStyle = .Gray
//        actIndicator.startAnimating()
        return actIndicator
    }()

}
